# -*- coding: utf-8 -*-

from odoo import models, fields, api,_
from odoo.exceptions import UserError
from odoo.models import NewId
from odoo.osv import expression
import datetime
DEFAULT_SERVER_DATE_FORMAT = "%Y-%m-%d"
DEFAULT_SERVER_TIME_FORMAT = "%H:%M:%S"
DEFAULT_SERVER_DATETIME_FORMAT = "%s %s" % (
    DEFAULT_SERVER_DATE_FORMAT,
    DEFAULT_SERVER_TIME_FORMAT)
class ResUsers(models.Model):
    _inherit = 'res.users'
    employee_ids = fields.One2many('hr.employee', 'user_id')
    @api.model
    def create(self, vals):
        user_id=super(ResUsers, self).create(vals)
        if user_id.login:
            barcode=user_id.login
            e=self.env['hr.employee'].sudo().search([('barcode','=',barcode)])
            if e:
                e.user_id=user_id.id
        return user_id



class ProductionLine(models.Model):
    _name = 'hr.production.line'
    _description = u'线别'
    name=fields.Char()

class hreducationline(models.Model):
    _name = 'hr.education.line'
    _description = u'学历'
    name=fields.Char()

class HREmployee(models.Model):

    """
    增加住宿栏位  ，选择项  内/外
    增加工龄栏位， 根据入厂日期自动计算，精确到月，如： 2年11月
    增加籍贯栏位
    增加居住地址栏位
    """
    _inherit = 'hr.employee'
    education_line_id=fields.Many2one('hr.education.line',string=u'学历')
    need_dom=fields.Selection([
        ('0','内'),
        ('1', '外'),
    ],string=u'住宿')
    native_place=fields.Char(string=u'籍贯')
    address_new=fields.Char(string=u'居住地址')

    work_month=fields.Char(compute='compute_work_month',string=u'工龄')
    def month_differ(self, first, second):
        month_differ = abs((first.year - second.year) * 12 + (first.month - second.month) * 1)
        month=month_differ%12
        year=int(month_differ/12)
        return year,month


    @api.depends('date_entry')
    def compute_work_month(self):
        for employee in self:
            employee.work_month ='0'
            if employee.date_entry:
                start=datetime.datetime.now()
                end=employee.date_entry
                year,month=self.month_differ(start,end)
                employee.work_month=str(year)+'年'+str(month)+'月'




    production_line_id=fields.Many2one('hr.production.line',string='线别',tracking=True)
    introduce_person=fields.Char(string='介绍人')
    remark=fields.Char(string='备注')
    has_work_card=fields.Selection([
        ('Y','是'),
        ('N', '否'),
    ],string=u'工牌发放',tracking=True)
    has_work_clothes=fields.Selection([
        ('Y','是'),
        ('N', '否'),
    ],string=u'工衣发放',tracking=True)
    need_dining_room=fields.Selection([
        ('Y','是'),
        ('N', '否'),
    ],string=u'公司食堂就餐',tracking=True)
    need_rent = fields.Selection([
        ('Y', '是'),
        ('N', '否'),
    ], string=u'公租房备案',tracking=True)


    def name_get(self):
        result = []
        for record in self:
            name = record.name
            if record.sudo().barcode:
                name = "%s:%s" % (record.name, record.sudo().barcode)
            result.append((record.id, name))
        return result

    def toggle_active(self):
        if len(self)>1:
            raise UserError('不允许批量归档')
        return super(HREmployee, self).toggle_active()
    @api.onchange('name')
    def onchange_name_self(self):
        if isinstance(self.id ,NewId) and self.name:
            employee_ids=self.env['hr.employee'].search([('name','=',self.name)])
            if len(employee_ids)>0:
                warning={}
                warning['message'] = '员工姓名有重复'
                result = {'warning': warning}
                return result
        if self.id and self.name:
            employee_ids = self.env['hr.employee'].search([('name', '=', self.name)])
            if len(employee_ids) > 1:
                warning = {}
                warning['message'] = '员工姓名有重复'
                result = {'warning': warning}
                return result





    @api.model
    def _name_search(self, name='', args=None, operator='ilike', limit=100, name_get_uid=None):
        args = args or []
        if operator == 'ilike' and not (name or '').strip():
            domain = []
        else:
            name=name.strip()
            domain = ['|', '|', ('barcode', operator, name), ('name', operator, name), ('pin', operator, name)]
        record_ids = self._search(expression.AND([args, domain]), limit=limit, access_rights_uid=name_get_uid)
        return models.lazy_name_get(self.browse(record_ids).with_user(name_get_uid))
    date_entry = fields.Date(string='入职日期')
    employee_type = fields.Selection([
        ('1', '月薪'),
        ('2', '日薪'),
        ('3', '小时工')
    ],string=u'职工类型')
    resign_date=fields.Date(string=u'离职日期')
    barcode = fields.Char(string="工号", help="ID used for employee identification.", groups="hr.group_hr_user",required=True,
                          copy=False)
    attendance_free=fields.Boolean(default=False,string='无需考勤')
    service_company_id=fields.Many2one('labor.service.company',string=u'劳务公司')
    hire_type=fields.Selection([
        ('1','正式工'),
        ('2', '小时工'),
    ],string=u'聘用形式')
    post_id=fields.Many2one('res.employee.post',string='职务')
    house_type = fields.Selection([
        ('1', '本地城镇'),
        ('2', '本地农业'),
        ('3', '本省城镇'),
        ('4', '本省农业'),
        ('5', '外省城镇'),
        ('6', '外省农业'),
    ], string='户口性质')
    nation_id = fields.Many2one('res.nation', string='民族')
    politic_type = fields.Selection([
        ('1', '党员'),
        ('2', '非党员'),
        ('3', '团员')
    ],string=u'政治面貌')
    certificate = fields.Selection([
        ('high', '高中/中专'),
        ('college', '大专'),
        ('bachelor', '本科'),
        ('master', '硕士'),
        ('other','其他')
    ], string='学历',  groups="hr.group_hr_user", tracking=True)

class HREmployeePublic(models.Model):
    _inherit = 'hr.employee.public'
    date_entry = fields.Date(string='入职日期')
    barcode=fields.Char()
    attendance_free = fields.Boolean(default=False, string='无需考勤')
    resign_date = fields.Date(string=u'离职日期')
    pin=fields.Char()
    employee_type = fields.Selection([
        ('1', '月薪'),
        ('2', '日薪'),
        ('3', '小时工')
    ],string=u'职工类型',tracking=True)
    hire_type=fields.Selection([
        ('1','正式工'),
        ('2', '小时工'),
    ],string=u'聘用形式')
    post_id=fields.Many2one('res.employee.post')
    house_type = fields.Selection([
        ('1', '本地城镇'),
        ('2', '本地农业'),
        ('3', '本省城镇'),
        ('4', '本省农业'),
        ('5', '外省城镇'),
        ('6', '外省农业'),
    ], string='户口性质')
    nation_id = fields.Many2one('res.nation', string='民族')
    service_company_id = fields.Many2one('labor.service.company', string=u'劳务公司')
    politic_type = fields.Selection([
        ('1', '党员'),
        ('2', '非党员'),
        ('3', '团员')
    ],string=u'政治面貌')
    certificate = fields.Selection([
        ('high', '高中/中专'),
        ('college', '大专'),
        ('bachelor', '本科'),
        ('master', '硕士'),
        ('other','其他')
    ], string='学历',  groups="hr.group_hr_user", tracking=True)

    production_line_id=fields.Many2one('hr.production.line',string='线别',tracking=True)
    introduce_person=fields.Char(string='介绍人')
    remark=fields.Char(string='备注')
    has_work_card=fields.Selection([
        ('Y','是'),
        ('N', '否'),
    ],string=u'工牌发放',tracking=True)
    has_work_clothes=fields.Selection([
        ('Y','是'),
        ('N', '否'),
    ],string=u'工衣发放',tracking=True)
    need_dining_room=fields.Selection([
        ('Y','是'),
        ('N', '否'),
    ],string=u'公司食堂就餐',tracking=True)
    need_rent = fields.Selection([
        ('Y', '是'),
        ('N', '否'),
    ], string=u'公租房备案',tracking=True)


    education_line_id=fields.Many2one('hr.education.line',string=u'学历')
    need_dom=fields.Selection([
        ('0','内'),
        ('1', '外'),
    ],string=u'住宿')
    native_place=fields.Char(string=u'籍贯')
    address_new=fields.Char(string=u'居住地址')

    work_month=fields.Char(compute='compute_work_month')
    def month_differ(self, first, second):
        return first.year - second.year,first.month - second.month
    @api.depends('date_entry')
    def compute_work_month(self):
        for employee in self:
            employee.work_month ='0'
            if employee.date_entry:
                year,month=self.month_differ((datetime.datetime.now(),
                                      datetime.datetime.strptime(
                                          employee.date_entry,
                                          '%Y-%m-%d')))
                employee.work_month=str(year)+'年'+str(month)+'月'






